<?php
namespace app\api\model;

use think\Model;
use think\facade\Request;
use think\facade\Validate;
use think\exception\ValidateException;
use other\Token;

class Models extends Model
{

    /**
     * 获取用户信息(用于路由的model)
     *
     * @return array
     */
    protected function token()
    {
        $data['token'] = Request::header('token');
        $rules = [
            'token' => 'require'
        ];
        $v = Validate::make($rules, []);
        $result = $v->check($data);
        if ( ! $result ) {
            throw new ValidateException('token验证失败');
        }
        $info = Token::decode($data['token']);
        return (array)$info['userInfo'];
    }

    /**
     * 获取用户id
     *
     * @return int|NULL
     */
    protected function _uid()
    {
        $uid = app('request')->userInfo['id'];
        if ( $uid ) {
            return $uid;
        }
        return $this->token()['id'];
    }

}